﻿using IcsSEMCtrl.Db;
using IcsSEMCtrl.Device.Observe;
using IcsSEMCtrl.Event;
using IcsSEMCtrl.Service.Logger;
using IcsSEMCtrl.Util.Client;
using Lifter.Device;
using Lifter.Global;
using Lifter.Global.Device;
using Lifter.Utility;
using Microsoft.VisualBasic.Devices;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using TKT.Lifter.CIM.Lifter.Device.Service;
using TKT.Lifter.CIM.Lifter.Event.Lifter;
using TKT.Lifter.CIM.Lifter.Global;
using TKT.Lifter.CIM.Lifter.Gui.Monitor.Popups;
using static TKT.Lifter.CIM.Lifter.Gui.Widget.EFUFanControl;

namespace TKT.Lifter.CIM.Lifter.Gui.Monitor.Panels
{
    public partial class SystemsDisplay : UserControl
    {
        private static SystemsDisplay systemsDisplay = null;
        private delegate void delegateUpdateIO(string name,short value);
        private delegate void delegateUpdateEFU(Observable name, bool status);
        private delegate void delegateUpdateCPUChart(float value);
        private delegate void DelegateShuttleSpeed(short value);
        private delegate void delegateUpdateProcessCPUChart();
        //private delegate void delegateUpdateEFURpm(string name, short rpm);
        private string DeviceName;
        private bool IOStatus;
        private string CurrentDeviceType;
        private LifterSEM LftSem;
        private bool IOSignalDisplayCancelFlag = false;
        private bool DCADataPageHistoryCancelFlag = false;
        private DateTimeConverter dateTimeConverter = new DateTimeConverter();
        List<DataStatisticsDao> dataStatisticList = new List<DataStatisticsDao>();
        private static object CDADataObject = new object();
        public static SystemsDisplay GetSystemsDisplay()
        {
            if (systemsDisplay == null)
            {
                systemsDisplay = new SystemsDisplay();
            }
            return systemsDisplay;
        }

        private SystemsDisplay()
        {
            InitializeComponent();
            CDADataDisplayEventAdapter cDADataDisplayEventAdapter = new CDADataDisplayEventAdapter();
            FanSenderEventAdapter fanSenderEventAdapter = new FanSenderEventAdapter();

            try
            {
                this.LftSem = (LifterSEM)Naming.GetDeviceManager().GetDevice();
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在[SystemsDisplay]构造方法中报错", ex);
            }
            //初始化权限
            InitPowerMenu();
            //初始化数据统计表
            this.InitStatisticTable();
            //初始化PIO表
            this.InitializePIODataGrid();
            //初始化时间数据统计图
            this.chartStatisticsControl.updateChartData();

            //PC数据面板启动；
            this.Start_Monitor();

            this.InitLoadTableData();
        }
        public void InitLoadTableData()
        {
            //初始化PIO查询开始时间，结束时间
            DateTime NowDay = DateTime.Now;
            string startDate = NowDay.ToString("yyyy-MM-dd" + " 08:30:00");
            string endDate = NowDay.ToString("yyyy-MM-dd" + " 20:30:00");
            this.QueryStartTime.Text = startDate;
            this.QueryEndTime.Text = endDate;

            //加载PIO查询下拉框Port集合
            this.CBPIOKeyWorld.Items.AddRange(this.LftSem.PortIDToHostID().ToArray());
        }
        private void InitStatisticTable()
        {
            try
            {
                this.DGVDataStatistic.AllowUserToAddRows = true;
                this.InitStatisticData();
                this.DGVDataStatistic.Columns[0].HeaderCell.Value = "时间日期";
                this.DGVDataStatistic.Columns[1].HeaderCell.Value = "设备单元";
                this.DGVDataStatistic.Columns[2].HeaderCell.Value = "搬送数量";
                this.DGVDataStatistic.Columns[3].HeaderCell.Value = "稼动率";;
                this.DGVDataStatistic.Columns[4].HeaderCell.Value = "搬送时间(秒)";
                this.DGVDataStatistic.Columns[5].HeaderCell.Value = "正常运行时间(秒)";
                this.DGVDataStatistic.Columns[6].HeaderCell.Value = "创建时间";
                this.DGVDataStatistic.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            }
            catch (Exception)
            {
            }
        }
        private void InitializePIODataGrid()
        {
            try
            {
                this.dgvPIOHistory.AllowUserToAddRows = false;
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns.Add(new DataGridViewTextBoxColumn());
                this.dgvPIOHistory.Columns[0].HeaderText = "序号";
                this.dgvPIOHistory.Columns[1].HeaderText = "PortID";
                this.dgvPIOHistory.Columns[2].HeaderText = "PIO交互信号";
                this.dgvPIOHistory.Columns[3].HeaderText = "PIO交互时间";
                this.dgvPIOHistory.Columns[4].HeaderText = "开始时间";
                this.dgvPIOHistory.Columns[5].HeaderText = "结束时间";

                this.dgvPIOHistory.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// 初始化页面权限
        /// </summary>
        public void InitPowerMenu()
        {
            List<MenuDao> menusOperation = GetMenuByPower(LftSem.UserPower);
            updatePowerForm(menusOperation);
            /*            if (LftSem.UserPower.Equals(enumUserManage.Operation.ToString()))
                        {
                            List<MenuDao> menusOperation = GetMenuByPower(enumUserManage.Operation.ToString());
                            updatePowerForm(menusOperation);
                        }
                        else if (LftSem.UserPower.Equals(enumUserManage.Management.ToString()))
                        {
                            List<MenuDao> menusManagement = GetMenuByPower(enumUserManage.Management.ToString());
                            updatePowerForm(menusManagement);
                        }*/
        }
        private void updatePowerForm(List<MenuDao> menuDaos)
        {
            foreach (MenuDao menu in menuDaos)
            {
                if (menu.ENNAME.Equals("IOSignalDisplay"))
                {
                    if (menu.MENUUSE.Equals("N"))
                    {
                        this.Controls["DisplayMenu"].Controls["IOSignalDisplay"].Enabled = false;
                    }
                    else
                    {
                        this.Controls["DisplayMenu"].Controls["IOSignalDisplay"].Enabled = true;
                    }
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        IOSignalDisplayCancelFlag = true;
                    }
                    else
                    {
                        IOSignalDisplayCancelFlag = false;
                    }
                }
                if (menu.ENNAME.Equals("DCADataPage"))
                {
                    if (menu.MENUUSE.Equals("N"))
                    {
                        this.Controls["DisplayMenu"].Controls["DCADataPage"].Enabled = false;
                    }
                    else
                    {
                        this.Controls["DisplayMenu"].Controls["DCADataPage"].Enabled = true;
                    }
                    if (menu.MENUDISPLAY.Equals("N"))
                    {
                        DCADataPageHistoryCancelFlag = true;
                    }
                    else
                    {
                        DCADataPageHistoryCancelFlag = false;
                    }
                }
            }
        }
        private List<MenuDao> GetMenuByPower(string PowerName)
        {
            DBConnection dBConnection = DBControl.GetConnection();
            List<MenuDao> menuLists = new List<MenuDao>();
            string sqlString = string.Format("SELECT USERMENU.ENNAME,USERMENU.CNNAME,USERMENUPOWER.MENUDISPLAY,USERMENUPOWER.MENUUSE" +
                                             " FROM USERMENU,USERMENUPOWER " +
                                             " WHERE USERMENU.ENNAME = USERMENUPOWER.MENUNAME " +
                                             " AND USERMENU.PARENTID = (SELECT ID FROM USERMENU WHERE USERMENU.ENNAME = '{0}') " +
                                             " AND USERMENUPOWER.POWERNAME = '{1}'", this.Name, PowerName);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                MenuDao menuDao = new MenuDao();
                menuDao.CNNAME = (string)sqlDataReader["CNNAME"];
                menuDao.ENNAME = (string)sqlDataReader["ENNAME"];
                menuDao.MENUDISPLAY = (string)sqlDataReader["MENUDISPLAY"];
                menuDao.MENUUSE = (string)sqlDataReader["MENUUSE"];
                menuLists.Add(menuDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return menuLists;
        }
        private class MenuDao
        {
            public string ENNAME { get; set; }
            public string CNNAME { get; set; }
            public string MENUDISPLAY { get; set; }
            public string MENUUSE { get; set; }
        }
        private class CDADataDisplayEventAdapter : ECPEventAdapter
        {
            public CDADataDisplayEventAdapter()
            {
                base.Subscribe();
            }
            public override string GetSubscriptionSubject()
            {
                return CDADataDisplayEvent.FormSubject("*");
            }

            public override void ReceiveECPEvent(ECPEvent ecpEvent)
            {
                SystemsDisplay.UpdateCDADataDisplayEvent(ecpEvent);
            }
        }
        /// <summary>
        /// 更新CDA数据实时显示
        /// </summary>
        /// <param name="eCPEvent"></param>
        public static void UpdateCDADataDisplayEvent(ECPEvent eCPEvent)
        {
            CDADataDisplayEvent cDADataDisplayEvent = (CDADataDisplayEvent)eCPEvent;
            lock (CDADataObject)
            {
                string name = cDADataDisplayEvent.name;
                short value = cDADataDisplayEvent.value;
                SystemsDisplay.GetSystemsDisplay().UpdateCDADataDelegate(name,value);
            }
        }
        public void UpdateCDADataDelegate(string name, short value)
        {
            lock (CDADataObject)
            {
                systemsDisplay.BeginInvoke(new delegateUpdateIO(UpdateCDAData), name,value);
            }
        }
        public void UpdateCDAData(string name,short value)
        {
            lock (CDADataObject)
            {
                if (this.plShuttleData.Controls.ContainsKey(name))
                {
                    foreach (Control item in this.plShuttleData.Controls)
                    {
                        if (item.Name.Equals(name))
                        {
                            item.Text = value.ToString();
                            return;
                        }
                    }
                }
                else if (this.plAmmeter1Data.Controls.ContainsKey(name))
                {
                    foreach (Control item in this.plAmmeter1Data.Controls)
                    {
                        if (item.Name.Equals(name))
                        {
                            item.Text = value.ToString();
                            return;
                        }
                    }
                }
                else if (this.plAmmeter2Data.Controls.ContainsKey(name))
                {
                    foreach (Control item in this.plAmmeter2Data.Controls)
                    {
                        if (item.Name.Equals(name))
                        {
                            item.Text = value.ToString();
                            return;
                        }
                    }
                }
                else if (this.plFloorCVData.Controls.ContainsKey(name))
                {
                    foreach (Control item in this.plFloorCVData.Controls)
                    {
                        if (item.Name.Equals(name))
                        {
                            item.Text = value.ToString();
                            return;
                        }
                    }
                }
            }
        }

        private void DisplayMenu_Selecting(object sender, TabControlCancelEventArgs e)
        {
            string tabPageName = e.TabPage.Name;
            if ("IOSignalDisplay".Equals(tabPageName))
            {
                e.Cancel = IOSignalDisplayCancelFlag;
            }
            else if ("DCADataPage".Equals(tabPageName))
            {
                e.Cancel = DCADataPageHistoryCancelFlag;
            }
        }

        /// <summary>
        /// TabControl控件中TabPage选项卡切换时的触发此事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DisplayMenu_SelectedIndexChanged(object sender, EventArgs e)
        {
            //当点击“数据统计显示”选项卡时逻辑
            if (DisplayMenu.SelectedIndex == 2)
            {
                this.chartStatisticsControl.updateChartData();
            }
            else if (DisplayMenu.SelectedIndex == 3)
            {
                this.Timer_Check_Div();
            }
            else if (DisplayMenu.SelectedIndex == 0)
            {
                this.InitLoadTableData();
            }
            
        }
        /// <summary>
        /// 根据用户选择的时间获取数据
        /// </summary>
        private List<DataStatisticsDao> GetStatisticDates(DateTime startTime, DateTime endTime)
        {
            List<DataStatisticsDao> dataStatistics = new List<DataStatisticsDao>();
            //判断用户输入结束时间不能小于开始时间
            if (endTime < startTime)
            {
                UIMessageDialog.ShowMessageDialog("结束时间不能小于开始时间", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                return dataStatistics;
            }
            //判断用户选择时间是否超过三个月
            TimeSpan intervalTime = endTime.AddMonths(-3) - startTime;
            double intervalTimeCount = intervalTime.TotalDays;
            if (intervalTimeCount >= 0)
            {
                UIMessageDialog.ShowMessageDialog("选择的时间不能超过三个月", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                return dataStatistics;
            }
            //查询数据
            DBConnection dBConnection = DBControl.GetConnection();
            string sqlString = string.Format("SELECT * FROM DATASTATISTICS WHERE '{0}' < DATETIME AND DATETIME < '{1}'", startTime, endTime);
            SqlDataReader sqlDataReader = dBConnection.ExecuteQuery(sqlString);
            while (sqlDataReader.Read())
            {
                DataStatisticsDao dataStatisticsDao = new DataStatisticsDao();
                dataStatisticsDao.DATETIME = (DateTime)sqlDataReader["DATETIME"];
                dataStatisticsDao.EQUIPMENTNAME = (string)sqlDataReader["EQUIPMENTNAME"];
                dataStatisticsDao.TRANSPORTQTY = (int)sqlDataReader["TRANSPORTQTY"];
                dataStatisticsDao.UTILIZATIONRATE = (double)sqlDataReader["UTILIZATIONRATE"];
                dataStatisticsDao.TRANSFERTIME = (int)sqlDataReader["TRANSFERTIME"];
                dataStatisticsDao.SYSTEMNOALARMTIME = (int)sqlDataReader["SYSTEMNOALARMTIME"];
                dataStatisticsDao.CREATETIME = (string)sqlDataReader["CREATETIME"];
                dataStatistics.Add(dataStatisticsDao);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            DBControl.RemoveDBConection(dBConnection);
            return dataStatistics;
        }
        private void StatisticPageSet(List<DataStatisticsDao> list)
        {
            this.DGVDataStatistic.DataSource = list;
            //设置分页控件总数
            StatisticDataPagination.TotalCount = list.Count();
            //设置分页控件每页数量
            StatisticDataPagination.PageSize = Convert.ToInt32(this.StatisticDataPageSize.Value);
            StatisticDataPagination.ActivePage = 1;
        }
        //初始化时间统计数据
        private void InitStatisticData()
        {
            this.StatisticDataEndTime.Text = DateTime.Today.ToString("yyyy-MM-dd");
            this.StatisticDataStartTime.Text = DateTime.Today.AddMonths(-1).ToString("yyyy-MM-dd");
            DateTime endTime = (DateTime)dateTimeConverter.ConvertFromString(this.StatisticDataEndTime.Text);
            DateTime startTime = (DateTime)dateTimeConverter.ConvertFromString(this.StatisticDataStartTime.Text);
            this.dataStatisticList = this.GetStatisticDates(startTime, endTime);
            this.StatisticPageSet(dataStatisticList);
        }
        private void btStatisticDataSearch_Click(object sender, EventArgs e)
        {
            DateTime endTime = (DateTime)dateTimeConverter.ConvertFromString(this.StatisticDataEndTime.Text);
            DateTime startTime = (DateTime)dateTimeConverter.ConvertFromString(this.StatisticDataStartTime.Text);
            this.dataStatisticList = this.GetStatisticDates(startTime, endTime);
            this.StatisticPageSet(dataStatisticList);
        }

        private void StatisticDataPagination_PageChanged(object sender, object pagingSource, int pageIndex, int count)
        {
            if (StatisticDataPagination.TotalCount >= pageIndex * count)
            {
                this.DGVDataStatistic.DataSource = dataStatisticList.GetRange((pageIndex - 1) * count, count);
            }
            else
            {
                this.DGVDataStatistic.DataSource = dataStatisticList.GetRange((pageIndex - 1) * count, (StatisticDataPagination.TotalCount - ((pageIndex - 1) * count)));
            }
        }

        private void StatisticDataPageSize_ValueChanged(object sender, int value)
        {

            //设置分页控件总数
            StatisticDataPagination.TotalCount = dataStatisticList.Count();
            //设置分页控件每页数量
            StatisticDataPagination.PageSize = Convert.ToInt32(this.StatisticDataPageSize.Value);
            StatisticDataPagination.ActivePage = 1;
        }


        ///<summary>
        ///Add by XSJ
        /// PC性能监测;CPU,内存，硬盘;
        ///</summary>

        //定量参数；
        private string LogPath = "D:\\V Project\\Lifter\\LOG\\BMDT\\LFTC\\Log\\Statistics\\PC\\TestLog.txt";
        private double Limit_Div = 0.6;
        private long RAMTotal;

        private int RunTime = 0;
        private int MinCount = 0;
        private int DayCount = 0;

        //硬件数据对象
        private PerformanceCounter cpu_Counter;
        private PerformanceCounter memory_Counter;
        private PerformanceCounter Process_Counter;
        private PerformanceCounter Process_RAMCounter;
        private Computer computer;

        ////饼图参数设置;
        //UIPieSeries Pie_series = new UIPieSeries();
        //UIPieOption Pie_Option = new UIPieOption();
        //UILegend Pie_legend = new UILegend();

        //检测进程对象名；
        private string ProcessName = "lifter";
        private string DiveName = "D:\\";

        /// <summary>
        /// IsFirst_Message 检测是否为第一次弹窗
        /// IsFirstCheck 是否第一次进程序；
        /// </summary>
        bool IsFirst_Message;
        bool IsFirstCheck;
        bool Div_flag = true;
        private System.Timers.Timer timer;

        private void Start_Monitor()
        {
            Set_chart_Cpu();
            Set_chart_RAM();
            RAMTotal = Get_RAMTotal();
            cpu_Counter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            memory_Counter = new PerformanceCounter("Memory", "Available MBytes");
            Process_Counter = new PerformanceCounter("Process", "% Processor Time", ProcessName);
            Process_RAMCounter = new PerformanceCounter("Process", "Working Set - Private", ProcessName);
            timer = new System.Timers.Timer();
            timer.Interval = 1000; // 1秒钟更新一次
            timer.Elapsed += new ElapsedEventHandler(GetSystermData);

            timer.Start();
        }
        private void GetSystermData(object sender, ElapsedEventArgs e)
        {
            timer.Stop();
            this.Timer_CPUTick();
            this.Timer_RAMTick();
            this.Timer_Check_ProcessTick();
            timer.Start();
        }
        private void Set_chart_Cpu()
        {
            chart_CPU.Series[0].BorderWidth = 2;
            chart_CPU.Series[1].BorderWidth = 2;

            chart_CPU.ChartAreas[0].AxisY.LabelStyle.Format = "0%";//格式化，为了显示百分号
            //chart_CPU.ChartAreas[0].AxisX.LabelStyle.Format = "0S";

            chart_CPU.ChartAreas[0].AxisY.Minimum = 0;
            //chart_CPU.ChartAreas[0].AxisY.Maximum = 1;
            chart_CPU.ChartAreas[0].AxisY.Interval = 0.2;
            //chart_CPU.ChartAreas[0].AxisX.Minimum = 0;
            //chart_CPU.ChartAreas[0].AxisX.Maximum = 10;
            //chart_CPU.ChartAreas[0].AxisX.Interval = 5;

        }

        private void Set_chart_RAM()
        {
            chart_RAM.Series[0].Color = Color.Orange;
            chart_RAM.Series[0].BorderWidth = 2;
            chart_RAM.Series[1].Color = Color.Blue;
            chart_RAM.Series[1].BorderWidth = 2;

            chart_RAM.ChartAreas[0].AxisY.LabelStyle.Format = "0%";
            //chart_RAM.ChartAreas[0].AxisX.LabelStyle.Format = "0S";

            chart_RAM.ChartAreas[0].AxisY.Minimum = 0;
            chart_RAM.ChartAreas[0].AxisY.Maximum = 1;
            chart_RAM.ChartAreas[0].AxisY.Interval = 0.2;

            //chart_RAM.ChartAreas[0].AxisX.Minimum = 0;
            //chart_RAM.ChartAreas[0].AxisX.Maximum = 10;
            //chart_RAM.ChartAreas[0].AxisX.Interval = 5;
        }


        private void Timer_CPUTick()
        {
            try
            {
                float cpuUsage = cpu_Counter.NextValue();
                systemsDisplay.BeginInvoke(new delegateUpdateCPUChart(ShowCPUChart),cpuUsage);
            }
            catch (Exception ex)
            {
                //日志;
            }
        }
        public void ShowCPUChart(float cpuUsage)
        {
            chart_CPU.Series[0].Points.AddXY(DateTime.Now.ToString("HH:mm:ss"), (cpuUsage + 10.00) / 100);
            double ShowData = Math.Round(cpuUsage, 1) + 10.00;
            PC_CPUData.Text = ShowData.ToString();
            // 控制只显示最近10个数据点
            if (chart_CPU.Series[0].Points.Count > 10)
            {
                chart_CPU.Series[0].Points.RemoveAt(0);
            }
        }
        private void Timer_RAMTick()
        {
            systemsDisplay.BeginInvoke(new delegateUpdateProcessCPUChart(ShowRAMChart));
        }
        public void ShowRAMChart()
        {
            try
            {
                float useMemory = 100 - (memory_Counter.NextValue() / (RAMTotal / 1024 / 1024)) * 100;
                chart_RAM.Series[0].Points.AddXY(DateTime.Now.ToString("HH:mm:ss"), (useMemory + 10) / 100);
                double ShowData = Math.Round(useMemory, 1) + 10.00;
                PC_RAMData.Text = ShowData.ToString();

                if (chart_RAM.Series[0].Points.Count > 10)
                {
                    chart_RAM.Series[0].Points.RemoveAt(0);
                }
            }
            catch (Exception ex)
            {
                //...
            }
        }
        private void Timer_Check_ProcessTick()
        {
            systemsDisplay.BeginInvoke(new delegateUpdateProcessCPUChart(ProcessCPU));
        }
        public void ProcessCPU()
        {
            try
            {
                bool IsProcessExist = IsProcessRunning(ProcessName);
                if (IsFirstCheck)
                {
                    IsFirst_Message = true;
                }
                if (IsProcessExist)
                {
                    float Process_CpuUsage = Process_Counter.NextValue();
                    chart_CPU.Series[1].Points.AddY(Process_CpuUsage / 100);
                    double Process_ShowData = Math.Round(Process_CpuUsage, 1);
                    Process_CPUData.Text = Process_ShowData.ToString();

                    if (chart_CPU.Series[1].Points.Count > 10)
                    {
                        chart_CPU.Series[1].Points.RemoveAt(0);
                    }

                    float Process_RAM = Process_RAMCounter.NextValue() / RAMTotal;
                    chart_RAM.Series[1].Points.AddY(Process_RAM);
                    double Pro_ShowData = Math.Round(Process_RAM * 100, 1);
                    Process_RAMData.Text = Pro_ShowData.ToString();

                    if (chart_RAM.Series[1].Points.Count > 10)
                    {
                        chart_RAM.Series[1].Points.RemoveAt(0);
                    }
                    if (IsFirst_Message)
                    {
                        IsFirst_Message = false;
                        MessageBox.Show($"检测到{ProcessName}进程！");
                    }
                }
                if (IsFirstCheck)
                {
                    IsFirst_Message = false;
                }
                if (!IsProcessExist)
                {
                    if (!IsFirst_Message)
                    {
                        IsFirst_Message = true;
                        MessageBox.Show($"检测到{ProcessName}进程未运行!");
                        Process_CPUData.Text = "00.0";
                        Process_RAMData.Text = "00.0";
                        chart_CPU.Series[1].Points.Clear();
                        chart_RAM.Series[1].Points.Clear();
                    }
                }
                IsFirstCheck = false;
            }
            catch (Exception ex)
            {
                //日志
            }
        }
        //检测进程是否存在；
        bool IsProcessRunning(string processName)
        {
            Process[] processes = Process.GetProcesses();
            foreach (Process process in processes)
            {
                if (process.ProcessName.Equals(processName, StringComparison.OrdinalIgnoreCase))
                {
                    return true;
                }
            }
            return false;
        }

        private void Timer_Check_Div()
        {
            try
            {
                DriveInfo driveInfo = new DriveInfo(DiveName);

                if (driveInfo.IsReady)
                {
                    long totalSizeInBytes = driveInfo.TotalSize;
                    long freeSpaceInBytes = driveInfo.AvailableFreeSpace;

                    // 转换为更友好的单位格式
                    //string totalSize = FormatSize(totalSizeInBytes);
                    //string freeSpace = FormatSize(freeSpaceInBytes);

                    float DivUsage = (float)freeSpaceInBytes / totalSizeInBytes;
                    double Div_UnUsageShow = Math.Round(DivUsage * 100, 1);
                    double Div_UsageShow = Math.Round((1 - DivUsage) * 100, 1);

                    Chart_Div_Show(Div_UsageShow, Div_UnUsageShow);

                    if (Div_UsageShow > Limit_Div && Div_flag)
                    {
                        Div_flag = false;
                        SendMessage();
                    }
                    else if (Div_UsageShow < Limit_Div)
                    {
                        Div_flag = false;
                    }
                }
                else
                {
                    Console.WriteLine("Drive is not ready.");
                }
            }
            catch (Exception ex)
            {
                //日志，上报
                LogHelper.loggerError("在Timer_Check_Div方法中报错", ex);
            }
        }

        private void Chart_Div_Show(double used, double unUsed)
        {
            var option = new UIPieOption();
            //设置Title
            option.Title = new UITitle();
            option.Title.Text = "系统盘占用(百分比%)";
            //option.Title.SubText = "Star";
            option.Title.Left = UILeftAlignment.Center;

            //设置ToolTip
            //  option.ToolTip.Visible = true;

            //设置Legend
            option.Legend = new UILegend();
            option.Legend.Orient = UIOrient.Vertical;
            option.Legend.Top = UITopAlignment.Bottom;
            option.Legend.Left = UILeftAlignment.Left;

            option.Legend.AddData("系统盘使用量");
            option.Legend.AddData("系统盘空闲量");

            //设置Series
            var series = new UIPieSeries();
            series.Name = "C:";
            series.Center = new UICenter(50, 55);
            series.Radius = 55;
            series.Label.Show = true;

            //增加数据
            series.AddData("系统盘使用量", unUsed);
            series.AddData("系统盘空闲量", used);

            //增加Series
            option.Series.Clear();
            option.Series.Add(series);

            //设置Option
            chart_Div.SetOption(option);
        }
        //unfinish
        private void SendMessage()
        {
            try
            {
                //...messageSend...
            }
            catch (Exception ex)
            {
                //日志
            }
        }

        private long Get_RAMTotal()
        {
            long totalMemoryBytes = (long)new ComputerInfo().TotalPhysicalMemory;
            return totalMemoryBytes;
        }

        
        private void btSearch_Click(object sender, EventArgs e)
        {
            List<PIOHistoryDao> pIOHistories = this.GetPIOHistoryData();
            if (pIOHistories.Count == 0)
            {
                PopupNotice.DialogPopups("查询数据为空" , "date is empty", enumPopupsType.Warning);
            }
            else
            {
                this.PIODgvShow(pIOHistories);
            }
        }
        private void PIODgvShow(List<PIOHistoryDao> piodatas)
        {
            try
            {
                int index = 0;
                int rowNum = 1;
                if (piodatas != null && piodatas.Count() > 0)
                {
                    this.dgvPIOHistory.RowCount = piodatas.Count();
                    foreach (PIOHistoryDao pIOHistory in piodatas)
                    {
                        this.dgvPIOHistory.Rows[index].Cells[0].Value = rowNum;
                        this.dgvPIOHistory.Rows[index].Cells[1].Value = pIOHistory.PortID;
                        this.dgvPIOHistory.Rows[index].Cells[2].Value = pIOHistory.Value;
                        this.dgvPIOHistory.Rows[index].Cells[3].Value = pIOHistory.ValueTime;
                        this.dgvPIOHistory.Rows[index].Cells[4].Value = pIOHistory.CreateTime;
                        this.dgvPIOHistory.Rows[index].Cells[5].Value = pIOHistory.CompleteTime;
                        index++;
                        rowNum++;
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在查询PIO历史表，更新界面时报错", ex);
            }
        }
        public List<PIOHistoryDao> GetPIOHistoryData()
        {
            List<PIOHistoryDao> pIOHistories = new List<PIOHistoryDao>();
            string startTime = this.QueryStartTime.Text;
            string endTime = this.QueryEndTime.Text;
            string keyWord = this.CBPIOKeyWorld.Text;
            SqlDataReader sqlDataReader = null;
            try
            {
                DBConnection dBConnection = DBControl.GetConnection();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.Append("SELECT * FROM PORTPIOHISTORY WHERE 1 = 1 ");
                if (!string.IsNullOrEmpty(startTime))
                {
                    stringBuilder.Append($" AND CREATETIME >= '{startTime}'");
                }
                if (!string.IsNullOrEmpty(endTime))
                {
                    stringBuilder.Append($" AND CREATETIME <= '{endTime}'");
                }
                if (!string.IsNullOrEmpty(keyWord))
                {
                    stringBuilder.Append($" AND PORTID LIKE '%{keyWord}%'");
                }
                sqlDataReader = dBConnection.ExecuteQuery(stringBuilder.ToString());
                while (sqlDataReader.Read())
                {
                    PIOHistoryDao pIOHistoryDao = new PIOHistoryDao();
                    pIOHistoryDao.PortID = sqlDataReader["PORTID"].ToString();
                    pIOHistoryDao.Value = sqlDataReader["VALUE"].ToString();
                    pIOHistoryDao.ValueTime = sqlDataReader["VALUETIME"].ToString();

                    pIOHistoryDao.CreateTime = sqlDataReader["CREATETIME"].ToString();
                    pIOHistoryDao.CompleteTime = sqlDataReader["COMPLETETIME"].ToString();

                    pIOHistories.Add(pIOHistoryDao);
                }
                if (sqlDataReader != null)
                {
                    sqlDataReader.Close();
                }
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在方法GetPIOHistoryData中报错", ex);
                PopupNotice.DialogPopups("查询失败，错误代码 :" + ex.Message, "Query failed with error code: " + ex.Message, enumPopupsType.Error);
            }
            if (sqlDataReader != null)
            {
                sqlDataReader.Close();
            }
            return pIOHistories;
        }

        private void dgvPIOHistory_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            try
            {
                if (e.RowIndex >= 0)
                {
                    DataGridViewRow row = dgvPIOHistory.Rows[e.RowIndex];
                    string valueData = row.Cells[2].Value.ToString();
                    string valueTimeData = row.Cells[3].Value.ToString();
                    if (!string.IsNullOrEmpty(valueData) && !string.IsNullOrEmpty(valueTimeData))
                    {
                        this.PIOChartShow(valueData, valueTimeData);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void PIOChartShow(string pioValueData,string pioTimeData)
        {
            this.GetControl("pioChartpanel").Controls.RemoveByKey("chart");
            string[] PIOValueChar = pioValueData.Split(',');
            string[] PIOTimeChar = pioTimeData.Split(',');
            List<KeyValuePair<string, int>> dataPoints1 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints2 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints3 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints4 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints5 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints6 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints7 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints8 = new List<KeyValuePair<string, int>>();

            List<KeyValuePair<string, int>> dataPoints9 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints10 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints11 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints12 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints13 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints14 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints15 = new List<KeyValuePair<string, int>>();
            List<KeyValuePair<string, int>> dataPoints16 = new List<KeyValuePair<string, int>>();
            for (int i = 0; i < PIOValueChar.Length; i++)
            {
                char[] SensorArray = Convert.ToString(Convert.ToInt32(PIOValueChar[i]), 2).ToCharArray();
                char[] comChar;
                char[] char0 = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' };
                Array.Reverse(SensorArray);
                if (SensorArray.Length < 16)
                {
                    comChar = SensorArray.Concat(char0.Take(16 - SensorArray.Length)).ToArray();
                }
                else
                {
                    comChar = SensorArray;
                }
                dataPoints1.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[0].ToString()) + 3));
                dataPoints2.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[1].ToString()) + 6));
                dataPoints3.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[2].ToString()) + 9));
                dataPoints4.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[3].ToString()) + 12));
                dataPoints5.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[4].ToString()) + 15));
                dataPoints6.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[5].ToString()) + 18));
                dataPoints7.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[6].ToString()) + 21));
                dataPoints8.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[7].ToString()) + 24));

                dataPoints9.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[8].ToString()) + 27));
                dataPoints10.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[9].ToString()) + 30));
                dataPoints11.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[10].ToString()) + 33));
                dataPoints12.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[11].ToString()) + 36));
                dataPoints13.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[12].ToString()) + 39));
                dataPoints14.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[13].ToString()) + 42));
                dataPoints15.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[14].ToString()) + 45));
                dataPoints16.Add(new KeyValuePair<string, int>(PIOTimeChar[i], int.Parse(comChar[15].ToString()) + 48));
            }


            Series series1 = new Series();
            Series series2 = new Series();
            Series series3 = new Series();
            Series series4 = new Series();
            Series series5 = new Series();
            Series series6 = new Series();
            Series series7 = new Series();
            Series series8 = new Series();

            Series series9 = new Series();
            Series series10 = new Series();
            Series series11 = new Series();
            Series series12 = new Series();
            Series series13 = new Series();
            Series series14 = new Series();
            Series series15 = new Series();
            Series series16 = new Series();
            ChartArea chartArea = new ChartArea();

            series1.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series1.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series1.YValueType = ChartValueType.Double;
            series1.ChartType = SeriesChartType.StepLine;

            series2.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series2.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series2.YValueType = ChartValueType.Double;
            series2.ChartType = SeriesChartType.StepLine;

            series3.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series3.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series3.YValueType = ChartValueType.Double;
            series3.ChartType = SeriesChartType.StepLine;

            series4.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series4.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series4.YValueType = ChartValueType.Double;
            series4.ChartType = SeriesChartType.StepLine;

            series5.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series5.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series5.YValueType = ChartValueType.Double;
            series5.ChartType = SeriesChartType.StepLine;

            series6.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series6.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series6.YValueType = ChartValueType.Double;
            series6.ChartType = SeriesChartType.StepLine;

            series7.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series7.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series7.YValueType = ChartValueType.Double;
            series7.ChartType = SeriesChartType.StepLine;

            series8.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series8.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series8.YValueType = ChartValueType.Double;
            series8.ChartType = SeriesChartType.StepLine;

            series9.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series9.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series9.YValueType = ChartValueType.Double;
            series9.ChartType = SeriesChartType.StepLine;

            series10.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series10.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series10.YValueType = ChartValueType.Double;
            series10.ChartType = SeriesChartType.StepLine;

            series11.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series11.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series11.YValueType = ChartValueType.Double;
            series11.ChartType = SeriesChartType.StepLine;

            series12.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series12.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series12.YValueType = ChartValueType.Double;
            series12.ChartType = SeriesChartType.StepLine;

            series13.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series13.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series13.YValueType = ChartValueType.Double;
            series13.ChartType = SeriesChartType.StepLine;

            series14.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series14.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series14.YValueType = ChartValueType.Double;
            series14.ChartType = SeriesChartType.StepLine;

            series15.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series15.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series15.YValueType = ChartValueType.Double;
            series15.ChartType = SeriesChartType.StepLine;

            series16.ChartType = SeriesChartType.Line; // 或者其他你想要的图表类型  
            series16.XValueType = ChartValueType.String; // 设置X轴为DateTime类型  
            series16.YValueType = ChartValueType.Double;
            series16.ChartType = SeriesChartType.StepLine;

            // 添加数据点  
            foreach (var dataPoint in dataPoints1)
            {
                series1.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints2)
            {
                series2.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints3)
            {
                series3.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints4)
            {
                series4.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints5)
            {
                series5.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints6)
            {
                series6.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints7)
            {
                series7.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints8)
            {
                series8.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }

            foreach (var dataPoint in dataPoints9)
            {
                series9.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints10)
            {
                series10.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints11)
            {
                series11.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints12)
            {
                series12.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints13)
            {
                series13.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints14)
            {
                series14.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints15)
            {
                series15.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            foreach (var dataPoint in dataPoints16)
            {
                series16.Points.AddXY(dataPoint.Key, dataPoint.Value);
            }
            Chart chart = new Chart();
            chart.Name = "chart";
            chart.Series.Add(series1);
            chart.Series.Add(series2);
            chart.Series.Add(series3);
            chart.Series.Add(series4);
            chart.Series.Add(series5);
            chart.Series.Add(series6);
            chart.Series.Add(series7);
            chart.Series.Add(series8);

            chart.Series.Add(series9);
            chart.Series.Add(series10);
            chart.Series.Add(series11);
            chart.Series.Add(series12);
            chart.Series.Add(series13);
            chart.Series.Add(series14);
            chart.Series.Add(series15);
            chart.Series.Add(series16);



            chart.ChartAreas.Add(chartArea);

            chart.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd HH:mm:ss:fff"; // 设置X轴标签的格式
            chart.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Auto; // 如果是日期时间类型，设置间隔类型

            chart.ChartAreas[0].AxisY.LabelStyle.Format = ""; // 设置X轴标签的格式
            chart.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
            chart.ChartAreas[0].AxisY.MajorGrid.Enabled = true;
            chart.ChartAreas[0].AxisY.MajorGrid.LineDashStyle = ChartDashStyle.Dot;
            chart.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.Gainsboro;
            chart.ChartAreas[0].AxisY.IsLabelAutoFit = false;//
            // 清除现有的自定义标签（如果有的话）  
            chart.ChartAreas[0].AxisY.CustomLabels.Clear();

            // 添加自定义标签  
            CustomLabel cl1 = new CustomLabel(2.5, 3.5, "预留", 0, LabelMarkStyle.None);
            CustomLabel cl2 = new CustomLabel(5.5, 6.5, "AGV接/送第一层", 0, LabelMarkStyle.None);
            CustomLabel cl3 = new CustomLabel(8.5, 9.5, "AGV接/送第二层", 0, LabelMarkStyle.None);
            CustomLabel cl4 = new CustomLabel(11.5, 12.5, "AGV接/送料滚动", 0, LabelMarkStyle.None);
            CustomLabel cl5 = new CustomLabel(14.5, 15.5, "AGV接/送料完成", 0, LabelMarkStyle.None);
            CustomLabel cl6 = new CustomLabel(17.5, 18.5, "AGV送料请求", 0, LabelMarkStyle.None);
            CustomLabel cl7 = new CustomLabel(20.5, 21.5, "AGV接料请求", 0, LabelMarkStyle.None);
            CustomLabel cl8 = new CustomLabel(23.5, 24.5, "AGV状态信号", 0, LabelMarkStyle.None);

            CustomLabel cl9 = new CustomLabel(26.5, 27.5, "预留", 0, LabelMarkStyle.None);
            CustomLabel cl10 = new CustomLabel(29.5, 30.5, "EQ接/送第一层", 0, LabelMarkStyle.None);
            CustomLabel cl11 = new CustomLabel(32.5, 33.5, "EQ接/送第二层", 0, LabelMarkStyle.None);
            CustomLabel cl12 = new CustomLabel(35.5, 36.5, "EQ接/送料滚动", 0, LabelMarkStyle.None);
            CustomLabel cl13 = new CustomLabel(38.5, 39.5, "EQ接/送料完成", 0, LabelMarkStyle.None);
            CustomLabel cl14 = new CustomLabel(41.5, 42.5, "预留", 0, LabelMarkStyle.None);
            CustomLabel cl15 = new CustomLabel(44.5, 45.5, "EQ接/送料请求回复", 0, LabelMarkStyle.None);
            CustomLabel cl16 = new CustomLabel(47.5, 48.5, "EQ状态信号", 0, LabelMarkStyle.None);

            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl1);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl2);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl3);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl4);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl5);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl6);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl7);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl8);

            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl9);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl10);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl11);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl12);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl13);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl14);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl15);
            chart.ChartAreas[0].AxisY.CustomLabels.Add(cl16);
            chart.ChartAreas[0].AxisY.Minimum = 0;
            chart.ChartAreas[0].AxisY.Maximum = 50;
            chart.ChartAreas[0].AxisY.Interval = 3;
            chart.Dock = DockStyle.Fill;
            this.GetControl("pioChartpanel").Controls.Add(chart);
        }

        private async void btHighSpeed_Click(object sender, EventArgs e)
        {
            this.btHighSpeed.Enabled = false;
            if (this.LftSem.ShuttleMaster.ShuttleMasterStatus != enumRIDState.DOWN)
            {
                UIMessageDialog.ShowMessageDialog("轿厢不是Down状态，不能设置轿厢速度", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                this.btHighSpeed.Enabled = true;
                return;
            }
            try
            {
                Double highSpeedText = Math.Round(Convert.ToDouble(this.tbHighSpeed.Text),1);
                if (highSpeedText >= 2.7)
                {
                    UIMessageDialog.ShowMessageDialog("轿厢高速不能超过2.7m/s", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                    this.btHighSpeed.Enabled = true;
                    return;
                }
                short highSpeedWrite = (short)(highSpeedText * 10);
                await Task.Run(()=>
                {
                    this.LftSem.ShuttleMaster.O_SHUTTLEHIGHSPEEDVALUE = highSpeedWrite;
                    Thread.Sleep(500);
                    this.LftSem.ShuttleMaster.O_SHUTTLEHIGHSPEED = true;
                    Thread.Sleep(1000);
                    this.LftSem.ShuttleMaster.O_SHUTTLEHIGHSPEED = false;
                    LogHelper.operationLogger($"用户{this.LftSem.UserName}设置轿厢速度{highSpeedText}成功");
                });
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在设置轿厢速度时报错",ex);
            }
            this.btHighSpeed.Enabled = true;
        }
        private async void btMediumSpeed_Click(object sender, EventArgs e)
        {
            this.btMediumSpeed.Enabled = false;
            if (this.LftSem.ShuttleMaster.ShuttleMasterStatus != enumRIDState.DOWN)
            {
                UIMessageDialog.ShowMessageDialog("轿厢不是Down状态，不能设置轿厢速度", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                this.btMediumSpeed.Enabled = true;
                return;
            }
            try
            {
                Double mediumSpeed = Math.Round(Convert.ToDouble(this.tbMediumSpeed.Text), 1);
                if (mediumSpeed >= 1.3)
                {
                    UIMessageDialog.ShowMessageDialog("轿厢中速不能超过1.3m/s", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                    this.btMediumSpeed.Enabled = true;
                    return;
                }
                short highSpeedWrite = (short)(mediumSpeed * 10);
                await Task.Run(() =>
                {
                    this.LftSem.ShuttleMaster.O_SHUTTLEMEDIUMSPEEDVALUE = highSpeedWrite;
                    Thread.Sleep(500);
                    this.LftSem.ShuttleMaster.O_SHUTTLEMEDIUMSPEED = true;
                    Thread.Sleep(1000);
                    this.LftSem.ShuttleMaster.O_SHUTTLEMEDIUMSPEED = false;
                    LogHelper.operationLogger($"用户{this.LftSem.UserName}设置轿厢速度{mediumSpeed}成功");
                });
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在设置轿厢速度时报错", ex);
            }
            this.btMediumSpeed.Enabled = true;
        }

        private async void btLowSpeed_Click(object sender, EventArgs e)
        {
            this.btLowSpeed.Enabled = false;
            if (this.LftSem.ShuttleMaster.ShuttleMasterStatus != enumRIDState.DOWN)
            {
                UIMessageDialog.ShowMessageDialog("轿厢不是Down状态，不能设置轿厢速度", UILocalize.WarningTitle, showCancelButton: false, UIStyle.Orange, false, false);
                this.btLowSpeed.Enabled = true;
                return;
            }
            try
            {
                short lowSpeed = Convert.ToInt16(this.tbLowSpeed.Text);
                await Task.Run(() =>
                {
                    this.LftSem.ShuttleMaster.O_SHUTTLELOWSPEEDVALUE = lowSpeed;
                    Thread.Sleep(500);
                    this.LftSem.ShuttleMaster.O_SHUTTLELOWSPEED = true;
                    Thread.Sleep(1000);
                    this.LftSem.ShuttleMaster.O_SHUTTLELOWSPEED = false;
                });
                LogHelper.operationLogger($"用户{this.LftSem.UserName}设置轿厢速度{lowSpeed}成功");
            }
            catch (Exception ex)
            {
                LogHelper.loggerError("在设置轿厢速度时报错", ex);
            }
            this.btLowSpeed.Enabled = true;
        }
    }
}